package com.fingard.dsp.bank.directbank.jstzrcb01;

import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * @author dicke
 * @date 2018/9/16 13:45
 */
public class JSTZRCB01Transaction extends JSTZRCB01Base implements ITransaction{
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAts  = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();

        XmlTextWriter xmlWriter =  new XmlTextWriter();
        JSTZRCB01Header header =  new JSTZRCB01Header();
        String OpName = "B2EActTrsQry";
        header.transCode = OpName;
        header.reqSeqNo = p_req7516.reqHeader.transSeqID;
        xmlWriter.autoFormat = false;
        writeCommonHead(xmlWriter,header);
        write7516Loop(xmlWriter,0,p_req7516);

        String[] retStrArr = sendToBank(xmlWriter.toXmlString(),OpName);
        //从0开始，总页数减一
        int page = analysis7516Loop(retStrArr,retAts);

        for(int i = 1 ; i<= page ; i++){
            xmlWriter = new XmlTextWriter();
            xmlWriter.autoFormat = false;
            writeCommonHead(xmlWriter,header);

            write7516Loop(xmlWriter,i,p_req7516);
            retStrArr = sendToBank(xmlWriter.toXmlString(),OpName);
            page = analysis7516Loop(retStrArr,retAts);
        }

        if(page >= 0){
            retAts.writeRespCode("0");
            retAts.writeRespInfo("");
        }

        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;
        return 	d_7516_HisTrans(tmpReq7516);
    }

    private void write7516Loop(XmlTextWriter xmlWriter,int p_CurPage,Req7516HisTrans p_req7516){
        XElement tmpXElement = new XElement("Body", "");
        tmpXElement.addChild(new XElement("AcNo", p_req7516.actNum));
        tmpXElement.addChild(new XElement("BeginDate",p_req7516.dateFrom));
        tmpXElement.addChild(new XElement("EndDate",p_req7516.dateTo));
        tmpXElement.addChild(new XElement("requestPatches","10"));
        tmpXElement.addChild(new XElement("startPatches",(p_CurPage-1)*10 + ""));
        xmlWriter.writeXElement(tmpXElement);
        xmlWriter.writeEndElement();
        xmlWriter.writeEndDocument();
    }

    private int analysis7516Loop(String[] retStrArr,RetAtsTrans retAts)throws Exception{
        if(retStrArr[0].length() == 0){
            StringBuilder tmpSbMsg = new StringBuilder();
            XmlTextReader tmpBkReader = loadBankRespXmlReader(retStrArr[1], tmpSbMsg);

            if(tmpBkReader != null){
                String tmpRetCode = tmpBkReader.getFirstText("/Root/Head/OpRetCode");
                String tmpRetInfo = tmpBkReader.getFirstText("/Root/Head/OpRetMsg");
                String recordNumber = tmpBkReader.getSimpleText("recordNumber");
                if(BANK_RET_RIGHT_CODE.equals(tmpRetCode)){
                    RetAtsTransDetail detail =  new RetAtsTransDetail();
                    //银行返回明细解读路径，文档中未明确
                    String readedPath  = "/Root/Body/List";
                    while(tmpBkReader.read(readedPath)){
                        String cdFlagStr  = tmpBkReader.readedXElement.getSingleText("DCFlag").toUpperCase();
                        String  tranAmtStr = tmpBkReader.readedXElement.getSingleText("Amount");
                        if ("C".equals(cdFlagStr)) {
                            if (tranAmtStr.indexOf("-") >= 0) {
                                detail.cdFlag = "1";
                            } else {
                                detail.cdFlag = "2";
                            }
                        } else if ("D".equals(cdFlagStr)) {
                            if (tranAmtStr.indexOf("-") >= 0) {
                                detail.cdFlag = "2";
                            } else {
                                detail.cdFlag = "1";
                            }
                        } else {
                            retAts.writeRespCode("-1");
                            retAts.writeRespInfo( "借贷标志( " + cdFlagStr + ")无法识别，请与银行核对");
                            break;
                        }
                        detail.tranDate = tmpBkReader.readedXElement.getSingleText("TransDate");
                        detail.tranTime = tmpBkReader.readedXElement.getSingleText("TransTime");
                        detail.tranAmt = tmpBkReader.readedXElement.getSingleText("Amount").replace("-","");
                        detail.accBal = tmpBkReader.readedXElement.getSingleText("Balance");
                        detail.usage = tmpBkReader.readedXElement.getSingleText("Remark");
                        detail.recAccNum = tmpBkReader.readedXElement.getSingleText("OtherAcNo");
                        detail.recAccName = tmpBkReader.readedXElement.getSingleText("OtherName");
                        detail.valueDate = tmpBkReader.readedXElement.getSingleText("TransDate");
                        detail.abstr = pickupAbstr(detail.usage);
                        retAts.writeRetDetailWithoutRespCode(detail);
                    }
                    int page = 0;
                    if(!StringHelper.isNullOrEmpty(recordNumber)  && !StringHelper.isNullOrEmpty(recordNumber)) {
                        page = Integer.parseInt(recordNumber) / 10 + (Integer.parseInt(recordNumber) % 10 == 0 ? 0 : 1) - 1;
                    }//从0开始
                    else{
                        return -1;
                    }
                    return page;
                }
                else{
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpRetInfo);
                }
            }
            else{
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpSbMsg.toString());
            }
        }
        else{
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(retStrArr[1].toString());
        }
        return -1;
    }
}
